import plugin from '../../../lib/plugins/plugin.js'
import { Render } from '../components/index.js'


export class sign extends plugin {
    constructor() {
        super({
            name: '[xingchen-plugin] 签到',
            dsc: '[xingchen-plugin] 签到',
            event: 'message',
            priority: 1,
            rule: [
                {
                    reg: '^#?(鹿|🦌|打卡|陪一发|陪一管)$',
                    fnc: 'lu'
                },
                {
                    reg: '^#?补(鹿|🦌|打卡|撸)([0-9]+)$',
                    fnc: 'bulu'
                },
                {
                    reg: '^#?戒(🦌|鹿|打卡|撸)([0-9]+)?$',
                    fnc: 'jielu'
                },
                {
                    reg: '^#?(鹿|🦌|打卡|撸管)记录$',
                    fnc: 'record'
                },
                {
                    reg: '^#?查(鹿|🦌|打卡|撸管).*$',
                    fnc: 'chalu'
                },
                {
                    reg: '^#?(戒|帮)?(鹿|🦌|打卡|撸管|撸)(榜|排行|排行榜)$',
                    fnc: 'rank'
                },
                {
                    reg: '^#?帮((鹿|🦌|打卡|撸).*|.*(鹿|🦌|打卡|撸))$',
                    fnc: 'banglu'
                }
            ]
        })
    }

    async lu(e) {
        date()
        const todayDate = await date()
        let dataday = todayDate.dataday
        let data = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));
        if (data == null) {
            data = {
                "year": todayDate.year,
                "month": todayDate.month,
                "name": e.sender.card,
                "Signinds": todayDate.Signinds,
                "signdey": new Array(42).fill(0),
                "frequency": 0,//本月签到总数
                "months": 0,//月签到次数 
                "jielu": 0,//戒撸天数
                "banglu": 0,//帮撸次数
            };
        }
        if (data.year != todayDate.year || data.month != todayDate.month) {
            data.year = todayDate.year;
            data.month = todayDate.month;
            data.Signinds = todayDate.Signinds;
            data.signdey = new Array(42).fill(0),
                data.frequency = 0;
            data.jielu = 0;
            data.banglu = 0;
        }
        if (data.Signinds[dataday] == 1) {
            data.Signinds[dataday] = 2;
            data.frequency = data.frequency + 1;
            data.signdey[dataday] = data.signdey[dataday] + 1;
            data.months = data.months + 1;
        } else if (data.Signinds[dataday] == 2) {
            data.signdey[dataday] = data.signdey[dataday] + 1;
            data.frequency = data.frequency + 1;
        } else if (data.Signinds[dataday] == 3) {
            data.Signinds[dataday] = 2;
            data.frequency = data.frequency + 1;
            data.signdey[dataday] = 1;
            data.months = data.months + 1;
            data.jielu = data.jielu - 1;
        }
        if (data.name != e.sender.card) {
            data.name = e.sender.card;
        }
        let groupdata = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:group${e.group_id}_sign`)) || {}
        groupdata[e.user_id] = {
            "lu": data.frequency,
            "jielu": data.jielu,
            "banglu": data.banglu
        }
        await redis.set(`Yunzai:xingchen-plugin:group${e.group_id}_sign`, JSON.stringify(groupdata))
        await redis.set(`Yunzai:xingchen-plugin:${e.user_id}_sign`, JSON.stringify(data))
        let Signin = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));
        return await Render.render('sign/index', {
            todayDate,
            Signin,
            element: 'default'
        }, { e, scale: 1.6 })
    };

    async bulu(e) {
        date()
        const todayDate = await date()
        let mag = JSON.parse(e.msg.replace(/#?补(🦌|鹿|打卡|撸)/, ''))
        let day = mag + todayDate.firstDay - 1;
        if (mag > todayDate.daysInMonth) {
            return await e.reply(`${mag}号不存在哦~`, true);
        }
        if (mag >= todayDate.date) {
            return await e.reply(`不能补🦌还没到的时间哦~`, true);
        }
        let data = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));
        if (data == null) {
            return await e.reply(`你还没有🦌过哦~`, true);
        } else if (data.Signinds[day] == 1) {
            data.Signinds[day] = 2;
            data.frequency = data.frequency + 1;
            data.signdey[day] = data.signdey[day] + 1;
            data.months = data.months + 1;
        } else if (data.Signinds[day] == 2) {
            return await e.reply(`${mag}号你已经🦌了${data.signdey[day]}次~\n本月${daysInMonth}天你🦌了${data.frequency}次`, true);
        } else if (data.Signinds[day] == 3) {
            data.signdey[day] = 1;
            data.Signinds[day] = 2;
            data.frequency = data.frequency + 1;
            data.months = data.months + 1;
            data.jielu = data.jielu - 1;
        }
        if (data.name != e.sender.card) {
            data.name = e.sender.card;
        }

        let groupdata = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:group${e.group_id}_sign`)) || {}
        groupdata[e.user_id] = data.frequency
        await redis.set(`Yunzai:xingchen-plugin:group${e.group_id}_sign`, JSON.stringify(groupdata))
        await redis.set(`Yunzai:xingchen-plugin:${e.user_id}_sign`, JSON.stringify(data))
        let Signin = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));

        return await Render.render('sign/index', {
            todayDate,
            Signin,
            element: 'default'
        }, { e, scale: 1.6 })
    };

    async jielu(e) {
        date()
        const todayDate = await date()
        let ce = /\d/.test(e.msg)
        let mag
        if (ce == false) {
            mag = todayDate.date
        } else {
            mag = JSON.parse(e.msg.replace(/#?戒(🦌|鹿|打卡|撸)/, ''))
        }
        let day = mag + todayDate.firstDay - 1;
        if (mag > todayDate.daysInMonth) {
            return await e.reply(`${mag}号不存在哦~`, true);
        }
        if (mag > todayDate.date) {
            return await e.reply(`${mag}号没到哦~`, true);
        }
        let data = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));
        if (data == null) {
            data = {
                "year": todayDate.year,
                "month": todayDate.month,
                "name": e.sender.card,
                "Signinds": todayDate.Signinds,
                "signdey": new Array(42).fill(0),
                "frequency": 0,//本月签到总数
                "months": 0,//月签到次数 
                "jielu": 0,//戒撸天数
                "banglu": 0,//帮撸次数
            };
            data.signdey[day] = data.signdey[day] - 1;
            data.jielu = data.jielu + 1;
        } else if (data.year != todayDate.year || data.month != todayDate.month) {
            data.year = todayDate.year;
            data.month = todayDate.month;
            data.Signinds = todayDate.Signinds;
            data.signdey = new Array(42).fill(0),
                data.frequency = 0;
            data.jielu = 0;
            data.banglu = 0;
        } else {
            data.signdey[day] = data.signdey[day] - 1;
            data.jielu = data.jielu + 1;
        }
        if (data.signdey[day] >= 1) {
            data.frequency = data.frequency - 1;
        } else if (data.signdey[day] == 0) {
            data.months = data.months - 1;
            data.Signinds[day] = 1;
            data.frequency = data.frequency - 1;
        } else if (data.signdey[day] <= -1) {
            data.Signinds[day] = 3;
            data.signdey[day] = -1;
        }
        if (data.name != e.sender.card) {
            data.name = e.sender.card;
        }
        let groupdata = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:group${e.group_id}_sign`)) || {}
        groupdata[e.user_id] = {
            "lu": data.frequency,
            "jielu": data.jielu,
            "banglu": data.banglu
        }
        await redis.set(`Yunzai:xingchen-plugin:group${e.group_id}_sign`, JSON.stringify(groupdata))
        await redis.set(`Yunzai:xingchen-plugin:${e.user_id}_sign`, JSON.stringify(data))
        let Signin = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));

        return await Render.render('sign/index', {
            todayDate,
            Signin,
            element: 'default'
        }, { e, scale: 1.6 })
    };

    async record(e) {
        date()
        const todayDate = await date()
        let Signin = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`));
        if (Signin == null) {
            return await e.reply(`你还没有🦌过哦~`, true);
        } else {
            return await Render.render('sign/index', {
                todayDate,
                Signin,
                element: 'default'
            }, { e, scale: 1.6 })
        }
    }

    async chalu(e) {
        date()
        const todayDate = await date()
        let dataday = todayDate.dataday
        let data = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.at}_sign`));
        if (data == null) {
            return await e.reply(`没有查到🦌记录哦~`, true);
        } else if (data.year != todayDate.year || data.month != todayDate.month) {
            data.year = todayDate.year;
            data.month = todayDate.month;
            data.Signinds = todayDate.Signinds;
            data.frequency = 0;
        }
        let groupdata = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:group${e.group_id}_sign`)) || {}
        groupdata[e.user_id] = data.frequency
        await redis.set(`Yunzai:xingchen-plugin:group${e.group_id}_sign`, JSON.stringify(groupdata))
        await redis.set(`Yunzai:xingchen-plugin:${e.at}_sign`, JSON.stringify(data))
        let Signin = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.at}_sign`));
        return await Render.render('sign/index', {
            todayDate,
            Signin,
            element: 'default'
        }, { e, scale: 1.6 })
    }

    async rank(e) {
        date()
        const todayDate = await date()
        let groupdata = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:group${e.group_id}_sign`))
        if (!groupdata) {
            return await e.reply(`这个群没有人🦌过哦~`, true);
        } else {
            const arr = Object.entries(groupdata);
            let jie = e.msg.indexOf("戒")
            let bang = e.msg.indexOf("帮")
            let title = " "
            if (jie == 0) {
                arr.sort((a, b) => b[1].jielu - a[1].jielu);
                title = "戒🦌榜"
            } else if (bang == 0) {
                arr.sort((a, b) => b[1].banglu - a[1].banglu);
                title = "帮🦌榜"
            } else {
                arr.sort((a, b) => b[1].lu - a[1].lu);
                title = "🦌管榜"
            }
            let ranklist = [];
            for (let i = 0; i < arr.length; i++) {
                let data = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${arr[i][0]}_sign`));
                let rankcount
                if (data.month != todayDate.month) {
                    continue
                }
                if (title == "戒🦌榜") {
                    rankcount = data.jielu
                }
                if (title == "帮🦌榜") {
                    rankcount = data.banglu
                }
                if (title == "🦌管榜") {
                    rankcount = data.frequency
                }
                if (rankcount == 0) {
                    continue
                }
                let rank = {
                    id: arr[i][0],
                    name: data.name,
                    count: rankcount,
                }
                ranklist.push(rank);
            }
            return await Render.render('sign/rank', {
                todayDate,
                ranklist,
                title,
                element: 'elem'
            }, { e, scale: 1.6 })
        }
    }

    async banglu(e) {
        date()
        const todayDate = await date()
        let dataday = todayDate.dataday
        let bot_id = this.e.bot.uin
        console.log("账号：机器人+at",bot_id , e.at)
        if (e.at == null || e.at == bot_id) {
            return await e.reply(`不能帮机器人🦌哦~`, true);
        } else {
            let data = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.at}_sign`));
            let data1 = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.user_id}_sign`))
            if (data == null) {
                let nameurl = `https://api.leafone.cn/api/qqnick?qq=${e.at}`
                let nameapi = await fetch(nameurl)
                let nameapijx = await nameapi.json();
                let name = nameapijx.data.nickname
                data = {
                    "year": todayDate.year,
                    "month": todayDate.month,
                    "name": name,
                    "Signinds": todayDate.Signinds,
                    "signdey": new Array(42).fill(0),
                    "frequency": 0,//本月签到总数
                    "months": 0,//月签到次数 
                    "jielu": 0,//戒撸天数
                    "banglu": 0,//帮撸次数
                };
            }
            if (data.year != todayDate.year || data.month != todayDate.month) {
                data.year = todayDate.year;
                data.month = todayDate.month;
                data.Signinds = todayDate.Signinds;
                signdey = new Array(42).fill(0);
                data.frequency = 0;
            }
            if (data.Signinds[dataday] == 1) {
                data.Signinds[dataday] = 2;
                data.frequency = data.frequency + 1;
                data.signdey[dataday] = data.signdey[dataday] + 1;
                data.months = data.months + 1;
                data1.banglu = data1.banglu + 1
            } else if (data.Signinds[dataday] == 2) {
                return await e.reply(`他今天已经🦌过了哦~`, true);
            } else if (data.Signinds[dataday] == 3) {
                data.Signinds[dataday] = 2;
                data.frequency = data.frequency + 1;
                data.signdey[dataday] = data.signdey[dataday] + 1;
                data.months = data.months + 1;
                data1.banglu = data1.banglu + 1
                data.jielu = data.jielu - 1;
            }
            let groupdata = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:group${e.group_id}_sign`)) || {}
            groupdata[e.at] = {
                "lu": data.frequency,
                "jielu": data.jielu,
                "banglu": data.banglu
            }
            groupdata[e.user_id] = {
                "lu": data1.frequency,
                "jielu": data1.jielu,
                "banglu": data1.banglu
            }
            await redis.set(`Yunzai:xingchen-plugin:group${e.group_id}_sign`, JSON.stringify(groupdata))
            await redis.set(`Yunzai:xingchen-plugin:${e.at}_sign`, JSON.stringify(data))
            await redis.set(`Yunzai:xingchen-plugin:${e.user_id}_sign`, JSON.stringify(data1))

            let Signin = JSON.parse(await redis.get(`Yunzai:xingchen-plugin:${e.at}_sign`));
            return await Render.render('sign/index', {
                todayDate,
                Signin,
                element: 'default'
            }, { e, scale: 1.6 })
        }
    }
}

async function date() {
    const year = new Date().getFullYear();
    const month = new Date().getMonth() + 1;
    const date = new Date().getDate();
    const firstDay = new Date(year, month - 1, 1).getDay();
    const daysInMonth = new Date(year, month, 0).getDate(); // 获取当前月份的天数
    const formattedDate = `${year}年${month}月${date}日`;
    const dataday = firstDay + date - 1;
    const calendar = new Array(42).fill(null);
    for (let i = firstDay; i < firstDay + daysInMonth; i++) {
        calendar[i] = i - firstDay + 1;
    };
    const Signinds = new Array(42).fill(0);
    for (let x = firstDay; x < firstDay + daysInMonth; x++) {
        Signinds[x] = 1;
    };

    const todayDate = {
        year,
        month,
        date,
        firstDay,
        daysInMonth,
        formattedDate,
        dataday,
        calendar,
        Signinds
    };
    return todayDate;
}